package com.zb.jnlxc.service;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ZLHW.base.Exception.BaseErrorModel;
import com.ZLHW.base.Form.Page;
import com.ZLHW.base.dao.ListQueryCondition;
import com.ZLHW.base.dao.QueryCondition;
import com.ZLHW.base.service.BaseService;
import com.zb.jnlxc.dao.MouldDAO;
import com.zb.jnlxc.dao.PaiChanMouldDAO;
import com.zb.jnlxc.dao.PaiChanRecordDAO;
import com.zb.jnlxc.dao.SchemeDAO;
import com.zb.jnlxc.form.MiniPageReq;
import com.zb.jnlxc.model.*;
import com.zb.jnlxc.model.Mould.MODEL_STATUS;

@Transactional
@Service
public class MouldService extends BaseService<MouldDAO, Mould, Integer> {
    private static final Logger log = LoggerFactory.getLogger(MouldService.class);
    @Resource
    private SchemeDAO           schemeDao;
    @Resource
    private FlowService         flowService;
    @Resource
    private MouldFlowService    mouldFlowService;
    @Resource
    private PaiChanRecordDAO    paiChanRecordDAO;
    @Resource
    private PaiChanMouldDAO     paiChanMouldDAO;
    @Resource
    private DataDictService     dataDictService;
    @Resource
    private NotifyFlowService   notifyFlowService;

    /**
     * 生成模具编号
     */
    public String generateCode(Integer schemeId) {
        //图纸的下一个模具号
        Scheme scheme = schemeDao.getById(schemeId);
        int modelNum = scheme.getNextMouldNum();
        return scheme.getName() + "-" + String.format("%03d", modelNum);
    }

    /**
     * 保存模具，开启新的流程
     * @param mould
     * @return
     * @throws BaseErrorModel
     */
    public Mould saveMould(Mould mould, Admin user) throws BaseErrorModel {
        this.getDao().refresh(mould.getManufacture());
        mould.setLjcl(0);
        mould.setMouldRecordCount(0);
        mould.setCurrentState((byte) 1);//修改为流程中状态
//        mould.setStatus(MODEL_STATUS.定制.getValue());
        mould.setManuDate(new Date());
        mould.setSyxc(0);
        if (mould.getManufacture() == null) {
            mould.setFinishedBySelf(false);
        }
        this.create(mould);

        //更新图纸的下一个模具号
        schemeDao.refresh(mould.getScheme());
        Scheme scheme = mould.getScheme();
        scheme.setNextMouldNum(scheme.getNextMouldNum() + 1);
        this.schemeDao.update(scheme);
        if(mould.getStatus()==3){
            mouldFlowService.fixMould(mould,null);
        }else {
            mouldFlowService.startmouldFlowByKey(mould);
            notifySample(mould, user);
        }
        return mould;
    }



    /**
     * 通知泡模收模确认
     * @param mould
     */
    public void notifySample(Mould mould, Admin admin) {
        getDao().refresh(mould.getJyhx());
        if (mould.getJyhx().getName().equals("交样")) {

            SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String notifyId = mould.getCode() + "-" + dateformat1.format(new Date()) + "-"
                              + System.currentTimeMillis();
            Map map = new HashMap();
            map.put("mouldId", mould.getDbId());
            map.put("schemeId", mould.getScheme().getDbId());
            notifyFlowService.startNotify(notifyId, admin.getAccount(), "", "样品单开单",
                "/content/order/sample.vm", "样品单开单", map);
        }
    }

    public void finishMouldBySelf(Integer mouldDbId) {
        Mould mould = loadById(mouldDbId);
        mould.setFinishedBySelf(true);
        mould.setFinishedDate(new Date());
        update(mould);
    }

    /**
     * 保存模具，完成流程任务
     * @param mould 模具
     * @param taskId 任务号
     * @return
     * @throws BaseErrorModel 
     */
    public Mould saveMould(Mould mould, String taskId, Admin user) throws BaseErrorModel {
        if (flowService.getContentMap(taskId, "payWay") != null) {
            String payWay = flowService.getContentMap(taskId, "payWay").toString();
            mould.setPayType(payWay);
            if ("厂方负担".equals(payWay))
                mould.setFeeCharge((Admin) flowService.getContentMap(taskId, "feeCharge"));
            else if ("客户负担".equals(payWay))
                mould.setMouldFee((String) flowService.getContentMap(taskId, "mouldFee"));
        }
        this.saveMould(mould, user);
        flowService.completeTask(taskId, user);
        return mould;
    }

    /**
     * 通过分页载入模具
     * @param page
     * @return
     */
    public Page LoadMould(Page page) {

        List<QueryCondition> queryConditions = new ArrayList();
        StringBuffer hql = new StringBuffer("from Mould t where 1=1 ");
        if (StringUtils.isNotEmpty(page.getParameter("key"))) {
            String key = page.getParameter("key");
            hql.append("and ( t.code like :key or t.mouldSize.size like :key )");
            queryConditions.add(new QueryCondition("key", "%" + key + "%"));
        }
        if (StringUtils.isNotBlank(page.getParameter("paiChanRecordId"))) {
            Integer paiChanRecordId = Integer.parseInt(page.getParameter("paiChanRecordId"));
            PaiChanRecord paiChanRecord = paiChanRecordDAO.getById(paiChanRecordId);
            Scheme scheme = paiChanRecord.getOrderForm().getScheme();
            hql.append("and  t.scheme =:scheme ");
            queryConditions.add(new QueryCondition("scheme", scheme));
            ProductTeam productTeam = paiChanRecord.getProductTeam();
            if(productTeam!=null){
                DataDict jitai = productTeam.getJitai();
                if(jitai!=null&& NumberUtils.isNumber(jitai.getStr1())){
                    hql.append("and  t.jyjx.dbId =:jyjxid ");
                    queryConditions.add(new QueryCondition("jyjxid",Integer.parseInt(jitai.getStr1())));
                }
            }
        }
        if (StringUtils.isNotBlank(page.getParameter("status"))) {
            Byte status = Byte.parseByte(page.getParameter("status"));
            hql.append("and  t.status =:status ");
            queryConditions.add(new QueryCondition("status", status));
        }
        hql.append("order by ").append(page.getSortKey()).append(" ").append(page.getSortOrder());
        this.getDao().findByPageWithTmpHQL(page, hql.toString(), queryConditions);
        return page;
    }

    public List<Mould> getUsedMouldListByScheme(Integer schemeId) {
        Scheme scheme = schemeDao.loadById(schemeId);
        return this.getDao().getUsedMouldListByScheme(scheme);
    }

    /**
     * 删除模具
     * @param mouldId
     * @throws BaseErrorModel
     */
    public void deleteMould(Integer mouldId) throws BaseErrorModel {
        Mould mould = getById(mouldId);
        flowService.deleteProcessInstanceCascade("mouldFlow." + mould.getCode());
        this.getDao().delete(mould);
    }

    /**
     * 更新模具
     * @param mould
     * @throws BaseErrorModel
     */
    public Mould updateMould(Mould mould) throws BaseErrorModel {
        this.getDao().getSession().refresh(mould.getScheme());
        this.update(mould);
        return mould;
    }

    /**
     * 报废模具
     * @throws BaseErrorModel 
     */
    public void scrapMould(Mould mould, Admin user) throws BaseErrorModel {
        Mould newMould = this.loadById(mould.getDbId());
        newMould.setScrap(mould.getScrap());
        newMould.setScrapDate(new Date());
        newMould.setRegister(user);
        newMould.setStatus(MODEL_STATUS.彻底报废.getValue());
        this.update(newMould);

    }

    /**
     * 查找该图纸的所有可用模具
     * @param schemeId
     * @return
     */
    public List<Mould> findAllNormalMouldsByScheme(Integer schemeId) {
        return this.getDao().findByHQL(
            "from Mould this where this.scheme.dbId=? and this.status=?", schemeId,
            MODEL_STATUS.合格入库.getValue());
    }

    public void delete(Mould mould) throws BaseErrorModel {
        if (mould.getEnable() == 0)
            super.delete(mould);
    }

    public List<Integer> getWaitProductScheme() {
        return findHql("select distinct  m.scheme.dbId from Mould m where m.status = ? ",
            MODEL_STATUS.已收模.getValue());
    }

    /**
     * 获取可生产的排产记录
     * @param page
     * @return
     */
    public MiniPageReq loadWaitingPaiChanRecord(MiniPageReq page) {
//        List<Integer> schemeIds = getWaitProductScheme();
//        if (CollectionUtils.isEmpty(schemeIds))
//            return page;
        List<QueryCondition> queryConditions = new ArrayList();
        StringBuffer hql = new StringBuffer("from PaiChanRecord t where 1=1 ");
        if (StringUtils.isNotEmpty(page.getParameter("code"))) {
            String code = page.getParameter("code");
            hql.append("and (t.orderCodes like :key or t.mouldCodes like :key) ");
            queryConditions.add(new QueryCondition("key", "%" + code + "%"));
        }
        if (StringUtils.isNotEmpty(page.getParameter("productTeamId"))) {
            String productTeamId = page.getParameter("productTeamId");
            hql.append("and t.productTeamId = :productTeamId ");
            queryConditions
                .add(new QueryCondition("productTeamId", Integer.parseInt(productTeamId)));
        }

//        hql.append(" and t.orderForm.scheme.dbId in(:schemeIds) ");
        hql.append(" and t.orderForm.currentState = 3 ");
        hql.append(" and t.jiYaFinished = false ");
        hql.append(" and t.finished = false ");
//        queryConditions.add(new ListQueryCondition("schemeIds", schemeIds));
        hql.append("order by ").append(page.getSortKey()).append(" ").append(page.getSortOrder());
        this.getDao().findByPageWithTmpHQL(page, hql.toString(), queryConditions);
        return page;
    }

    public MiniPageReq loadPaiChanRecord(MiniPageReq page) {
        List<QueryCondition> queryConditions = new ArrayList();
        StringBuffer hql = new StringBuffer("from PaiChanRecord t where  jiYaFinished=false and finished=false and paimo=false ");
        if (StringUtils.isNotEmpty(page.getParameter("code"))) {
            String code = page.getParameter("code");
            hql.append("and (t.orderCodes like :key or t.mouldCodes like :key) ");
            queryConditions.add(new QueryCondition("key", "%" + code + "%"));
        }
        if (StringUtils.isNotEmpty(page.getParameter("productTeamId"))) {
            String productTeamId = page.getParameter("productTeamId");
            hql.append("and t.productTeamId = :productTeamId ");
            queryConditions
                .add(new QueryCondition("productTeamId", Integer.parseInt(productTeamId)));
        }
        hql.append("order by ").append(page.getSortKey()).append(" ").append(page.getSortOrder());
        this.getDao().findByPageWithTmpHQL(page, hql.toString(), queryConditions);
        return page;
    }

    /**
     * 获取已收模的模具
     */
    public List<Mould> loadWaitingMould(Integer paichanRecordId) {
        PaiChanRecord paiChanRecord = paiChanRecordDAO.getById(paichanRecordId);
        Scheme scheme = paiChanRecord.getOrderForm().getScheme();
        return this.findHql("from Mould m where m.scheme=?", scheme);
//        return this.findHql("from Mould m where m.status=? and m.scheme=?",
//            MODEL_STATUS.已收模.getValue(), scheme);

    }

    public void paiMo(Integer recordId, Admin user) {
        PaiChanRecord paiChanRecord = paiChanRecordDAO.getById(recordId);
        String mouldList = paiChanRecord.getMouldIds();
        if (StringUtils.isEmpty(mouldList)) {
            throw new BaseErrorModel("请先分配模具", "");
        }
        paiChanRecord.setPaimo(true);
        paiChanRecordDAO.update(paiChanRecord);
        List<PaiChanMould> list = paiChanRecordDAO.findPaiChanMoulds(paiChanRecord);
        for (PaiChanMould paiChanMould : list) {
            Mould mould = paiChanMould.getMould();
            mould.setProductTeam(paiChanRecord.getProductTeam());
            mouldFlowService.notifyDistribute(paiChanMould.getMould(), user);
        }
    }

    public void selectMould(String mouldList, Integer recordId) {
        PaiChanRecord paiChanRecord = paiChanRecordDAO.loadById(recordId);
        paiChanRecord.setMouldIds(mouldList);
        String[] mouldIds = mouldList.split(",");
        String mouldCodes = "";
        for (int a = 0; a < mouldIds.length; a++) {
            Mould mould = getById(Integer.parseInt(mouldIds[a]));
            mouldCodes += mould.getCode();
            if (a != mouldIds.length - 1) {
                mouldCodes += ",";
            }
        }
        paiChanRecord.setMouldCodes(mouldCodes);
        paiChanRecordDAO.mouldUpdate(paiChanRecord);
    }
}
